package com.ocom.payhandle.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ocom.common.entity.master.EntityEcardRegCode;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.common.enums.MasterSlaveEnum;
import com.ocom.common.utils.DateUtil;
import com.ocom.common.utils.RandomUtil;
import com.ocom.mysql.aspect.DataSourceAspect;
import com.ocom.payhandle.dao.IDaoEcardRegCode;
import com.ocom.payhandle.service.EcardRegCodeService;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service
public class EcardRegCodeServiceImpl extends ServiceImpl<IDaoEcardRegCode, EntityEcardRegCode> implements EcardRegCodeService {


    //插入ecard_reg_code
    @Override
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.MASTER)
    public EntityEcardRegCode addRegCodeInfo(EntityEcardRegCode entityEcardRegCode) {

        Boolean flag = false;
        for (int i = 0;i<10;i++){
            String coder= RandomUtil.generateNumber(6);
            QueryWrapper<EntityEcardRegCode> queryWrapper =new QueryWrapper();
            queryWrapper.eq("com_id",entityEcardRegCode.getComId());
            queryWrapper.eq("reg_code", coder);
            queryWrapper.ge("end_time", new Date());
            EntityEcardRegCode ecardRegCode = this.getOne(queryWrapper);
            if(ecardRegCode==null){
                flag=true;
                entityEcardRegCode.setRegCode(coder);
                entityEcardRegCode.setEndTime(DateUtil.addDays(new Date(),1));
                break;
            }
        }
        if(!flag)  return  null;
        boolean df=  this.save(entityEcardRegCode);
        if(df){
            return  entityEcardRegCode;
        }
        return  null;
    }


}
